package com.hon.legionnaire.negocio.dao;

import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hon.legionnaire.negocio.vo.ParcelaVO;

@Service("parcelaDAO")
public class ParcelaDAO {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional(propagation = Propagation.REQUIRED)
	public void inserirParcela(ParcelaVO parcelaVO) {
		try {
			entityManager.persist(parcelaVO);
		} catch (Exception e) {
			throw new RuntimeException("Erro ao inserir parcela: " + e.getMessage(), e);
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void atualizarParcela(ParcelaVO parcelaVO) {
		try {
			entityManager.merge(parcelaVO);
		} catch (Exception e) {
			throw new RuntimeException("Erro ao atualizar parcela: " + e.getMessage(), e);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void removerParcela(ParcelaVO parcelaVO) {
		try {
			if (!entityManager.contains(parcelaVO)) {
				parcelaVO = entityManager.merge(parcelaVO);
			}
			entityManager.remove(parcelaVO);
		} catch (Exception e) {
			throw new RuntimeException("Erro ao remover parcela: " + e.getMessage(), e);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public ParcelaVO obterParcela(ParcelaVO parcelaVO) {
		try {
			return entityManager.find(ParcelaVO.class, parcelaVO.getCodigo());
		} catch (Exception e) {
			throw new RuntimeException("Erro ao buscar parcela: " + e.getMessage(), e);
		}
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public List<ParcelaVO> obterListaParcela() {
		try {
			List<ParcelaVO> lista = (List<ParcelaVO>) entityManager.createNamedQuery("loadAllParcela").getResultList();
			if ((lista != null) && (!lista.isEmpty())) {
				return lista;
			} else {
				return Collections.EMPTY_LIST;
			}
		} catch (Exception e) {
			throw new RuntimeException("Erro ao carregar todos os parcelas.", e);
		}
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

}